package httpHandle

import (
	"github.com/gin-gonic/gin"
	"github.com/wzh200x/webServer/constants"
	"github.com/wzh200x/webServer/httpHandle/service"
	"github.com/wzh200x/webServer/middleware/auth"
	"github.com/wzh200x/webServer/middleware/response"
)

// 使用service包中定义的请求和响应结构
type CreateOrderRequest service.CreateOrderRequest
type OrderResponse service.OrderResponse
type QueryOrderRequest service.QueryOrderRequest
type OrderQueryResponse service.OrderQueryResponse
type PayedOrderRequest service.PayedOrderRequest
type ShipOrderRequest service.ShipOrderRequest

// HandleCreateOrder 处理创建订单请求
func HandleCreateOrder(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	// 从上下文中获取用户信息
	userID, username := auth.GetCurrentUser(c)

	// 解析请求参数
	var req CreateOrderRequest
	if bindErr := c.ShouldBind(&req); bindErr != nil {
		err(constants.ErrUnknown, "无效的请求参数")
		return
	}

	// 转换为service层的请求结构
	serviceReq := service.CreateOrderRequest{
		Data:         req.Data,
		Goods:        req.Goods,
		GoodsContent: req.GoodsContent,
		GoodsPrice:   req.GoodsPrice,
	}

	// 调用service层创建订单
	order, errCode, errMsg := service.CreateOrder(userID, username, serviceReq)
	if errCode > 0 {
		err(errCode, errMsg)
		return
	}

	// 返回订单信息
	success(order)
}

// HandleQueryOrder 处理查询订单请求
func HandleQueryOrder(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	// 从上下文中获取用户信息
	_, username := auth.GetCurrentUser(c)

	// 解析请求参数
	var req QueryOrderRequest
	if bindErr := c.ShouldBind(&req); bindErr != nil {
		err(constants.ErrUnknown, "无效的请求参数")
		return
	}

	// 调用service层查询订单
	orders, errCode, errMsg := service.QueryOrdersByStatus(username, req.Status)
	if errCode > 0 {
		err(errCode, errMsg)
		return
	}

	// 返回订单信息
	success(orders)
}

// HandlePayedOrder 处理订单支付完成请求
func HandlePayedOrder(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	// 从上下文中获取用户信息
	_, username := auth.GetCurrentUser(c)

	// 解析请求参数
	var req PayedOrderRequest
	if bindErr := c.ShouldBind(&req); bindErr != nil {
		err(constants.ErrUnknown, "无效的请求参数")
		return
	}

	// 调用service层更新订单状态为已支付
	order, errCode, errMsg := service.UpdateOrderToPaid(username, req.Order)
	if errCode > 0 {
		err(errCode, errMsg)
		return
	}

	// 返回更新后的订单信息
	success(order)
}

// HandleShipOrder 处理订单发货请求
func HandleShipOrder(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	// 从上下文中获取用户信息
	_, username := auth.GetCurrentUser(c)

	// 解析请求参数
	var req ShipOrderRequest
	if bindErr := c.ShouldBind(&req); bindErr != nil {
		err(constants.ErrUnknown, "无效的请求参数")
		return
	}

	// 调用service层更新订单状态为已发货
	order, errCode, errMsg := service.UpdateOrderToShipped(username, req.Order)
	if errCode > 0 {
		err(errCode, errMsg)
		return
	}

	// 返回更新后的订单信息
	success(order)
}
